package dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import model.ClassDoublePojo;
import model.ClassPojo;
import model.PropPojo;

public class ClassDefDao {

	public void insertClassDouble(ClassPojo cla, PropPojo prop) {
		DBCon db = new DBCon();
		Connection con;
		try {
			con = db.getCon();

			// First check that an identical record doesn't already exist
			ClassDao cdao = new ClassDao();
			PropDao pdao = new PropDao();
			boolean doesItExist = doesDoubleExist(cla,prop);
			
System.out.println(doesItExist);

			if (doesItExist==false) {
				Statement stmt;
				stmt = con.createStatement();
				stmt.executeUpdate("INSERT INTO class_defs(class_def_cl, class_def_pr) values("+cdao.getClassId(cla.getClassUri()) + ","+ pdao.getPropId(prop.getPropUri())+")");
			}

		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public boolean doesDoubleExist(ClassPojo cla, PropPojo prop) {

		boolean doesItExist=true;

		DBCon db = new DBCon();
		Connection con;

		try {
			con = db.getCon();
			String classUri = cla.getClassUri();
			String propUri = prop.getPropUri();
			// get the classIds

			Statement stmt;
			stmt = con.createStatement();
			
			ClassDao cdao = new ClassDao();
			int classId = -1;
			PropDao pdao = new PropDao();
			int propId =-1;
			
			boolean doesClassExist = false;
			boolean doesPropExist = false;
			
			ResultSet rs1 = stmt.executeQuery("SELECT class_id FROM classes WHERE class_uri='"+classUri+"'");
			if(rs1.next()){
				doesClassExist = true;
				classId = cdao.getClassId(classUri);
System.out.println("Class Id: "+classId);

			}
			else{
				cdao.insertClassPojo(cla);
				classId = cdao.getClassId(classUri);
System.out.println("Class Id: "+classId);
			}

			doesPropExist = pdao.doesPropExist(prop);
			if(doesPropExist==true){
				propId = pdao.getPropId(propUri);
System.out.println("Prop Id: "+propId);
			}
			else{
				pdao.insertPropPojo(prop);		
				propId = pdao.getPropId(propUri);
System.out.println("Prop Id: "+propId);
			}
			
			ResultSet rs = stmt.executeQuery("SELECT class_def_id FROM class_defs WHERE class_def_cl="+ classId + " AND class_def_pr=" + propId+"");

			if (rs.next()) {
				doesItExist = true;
				System.out.println(rs.getInt("class_def_id"));
			} else {
				doesItExist = false;
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return doesItExist;
	}
}
